package com.yili.pda.dialog

import android.app.Activity
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.it.common.utils.DialogUtils
import com.it.common.utils.LogUtil
import com.it.data.manager.AppManager.FILE_PATH
import com.it.data.manager.HttpManager
import com.it.gw.R
import com.xuexiang.xupdate._XUpdate
import com.xuexiang.xupdate.utils.FileUtils


object UpdateDialog {
    const val TAG = "UpdateDialog"
    //        val intent: Intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setData(Uri.parse("package:$packageName"))
//        startActivity(intent)

    fun showUpdateDialog(url: String, versionName: String, context: Activity) {
        val updateDialog = DialogUtils.getDialogNotTouchOutside(context, R.layout.dialog_update)
        val version = updateDialog.findViewById<TextView>(R.id.version)
        val ivClose = updateDialog.findViewById<ImageView>(R.id.iv_close)
        val rlOk = updateDialog.findViewById<RelativeLayout>(R.id.rl_ok)
        val tvOk = updateDialog.findViewById<TextView>(R.id.tv_ok)
        version.text = versionName
        tvOk.isEnabled = true
        ivClose.setOnClickListener {
           // updateDialog.dismiss()
        }
        rlOk.setOnClickListener {
            tvOk.text = "开始下载..."
            tvOk.isEnabled = false
            downLoad(url = url, context = context, tvOk = tvOk, updateDialog = updateDialog)
        }
        updateDialog.show()

    }

    var idDownLoading = false;

    /**
     * 下载
     * @param url String?
     */
    private fun downLoad(
        url: String,
        context: Activity,
        tvOk: TextView,
        updateDialog: DialogUtils
    ) {
        if (idDownLoading) {
            return
        }
        url?.let {
            idDownLoading = true;
            HttpManager.downloadFile(
                url,
                FILE_PATH + "${System.currentTimeMillis()}_hm.apk",
                object : HttpManager.DownloadListener {
                    override fun onProgress(progress: Long, total: Long) {
                        LogUtil.d(TAG, "onProgress: $progress and $total")
                        val percentage = if (total != 0L) {
                            (progress.toDouble() / total.toDouble()) * 100
                        } else {
                            0.0 // 防止除以零的情况
                        }

                        val formattedPercentage = "%.2f%%".format(percentage)
                        context.runOnUiThread {
                            if (updateDialog.isShowing) {
                                tvOk.text = "正在下载：$formattedPercentage"
                            }
                        }
                    }

                    override fun onSuccess(filePath: String) {
                        LogUtil.d(TAG, "onSuccess: ${filePath} ")
                        context.runOnUiThread {
                            if (updateDialog.isShowing) {
                                tvOk.text = "下载成功，正在安装"
                                updateDialog.dismiss()
                            }
                        }
                        idDownLoading = false;
                        _XUpdate.startInstallApk(
                            context,
                            FileUtils.getFileByPath(
                                filePath
                            )!!
                        ); // Set the path where the file is located

                    }

                    override fun onFail(msg: String?) {
                        LogUtil.d(TAG, "onFail: $msg ")
                        context.runOnUiThread {
                            if (updateDialog.isShowing) {
                                tvOk.text = "下载失败 $msg"
                            }
                        }
                        idDownLoading = false;


                    }

                })
        }

    }
}